//
//  CollectionController.m
//  jang
//
//  Created by lee han on 15/04/2017.
//  Copyright © 2017 lee han. All rights reserved.
//

#import "CollectionController.h"
#import "CommonView.h"
#import "CRUserData.h"
#import "ProductCell.h"
#import "UIImageView+WebCache.h"
#import "ProductInfoController.h"

@interface CollectionController ()

@end

@implementation CollectionController

-(void)requestCollection:(NSInteger)page{
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%ld", (long)(page)], @"page",
                                 nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_cellection];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationItem.backBarButtonItem setTitle:@""];
    [_mTableView registerNib:[UINib nibWithNibName:@"ProductCell" bundle:nil] forCellReuseIdentifier:@"CellectProductCell"];
    _mTableView.delegate = self;
    _mTableView.dataSource = self;
    
    _mTextCount.hidden = YES;
    
    
    mMaxPage = 0;
    mCurrentPage = 1;
    mListData = [[NSMutableArray alloc] init];
    
    //请求收藏信息
    [self requestCollection: 0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshView{
    _mTextCount.text = [NSString stringWithFormat:@"共%ld件商品", [[CRUserData sharedInstance] CollectionCount]];
    _mTextCount.hidden = NO;
    
    NSInteger count = [mListData count];
    mRowCount = count / 2 + (count % 2 > 0 ? 1 : 0) + 1;
    [_mTableView reloadData];
}

-(void)onClickMore:(id)sender{
    if(mCurrentPage >= mMaxPage)
        return;
    [self requestCollection:mCurrentPage];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < mRowCount - 1)
        return 186;
    return 30;
}

//end UITableViewDelegate

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return mRowCount;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == mRowCount - 1){
        UITableViewCell* lastcell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        lastcell.backgroundColor = [UIColor clearColor];
        
        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        
        button.backgroundColor = [UIColor clearColor];
        
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        if(mCurrentPage < mMaxPage){
            [button setTitle:@"点击加载更多" forState:UIControlStateNormal];
        }
        else{
            [button setTitle:@"" forState:UIControlStateNormal];
        }
        
        [button addTarget:self action:@selector(onClickMore:) forControlEvents:UIControlEventTouchUpInside];
        
        [lastcell addSubview:button];
        
        return lastcell;
        
    }
    ProductCell *cell = [_mTableView dequeueReusableCellWithIdentifier:@"CellectProductCell" forIndexPath:indexPath];
    
    cell.mButton2.hidden = YES;
    
    NSInteger index = indexPath.row * 2;
    cell.mButton1.mName.text = [[mListData objectAtIndex:index] objectForKey:@"pname"];
    cell.mButton1.mPrice.text = [[mListData objectAtIndex:index] objectForKey:@"price"];
    
    NSString* urlstr = [URLIMAGE_PRE stringByAppendingString:[[mListData objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton1.mImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    
    NSString* pid = [[mListData objectAtIndex:index] objectForKey:@"id"];
    
    [cell.mButton1.mButton setTitle:@"删除" forState:UIControlStateNormal];
    
    cell.mButton1.mProductID = [pid integerValue];
    cell.mButton1.mDelegate = self;
    
    ++index;
    if(index >= [mListData count])
        goto end;
    cell.mButton2.hidden = NO;
    cell.mButton2.mName.text = [[mListData objectAtIndex:index] objectForKey:@"pname"];
    cell.mButton2.mPrice.text = [[mListData objectAtIndex:index] objectForKey:@"price"];
    
    urlstr = [URLIMAGE_PRE stringByAppendingString:[[mListData objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton2.mImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    
    pid = [[mListData objectAtIndex:index] objectForKey:@"id"];
    [cell.mButton2.mButton setTitle:@"删除" forState:UIControlStateNormal];
    cell.mButton2.mProductID = [pid integerValue];
    cell.mButton2.mDelegate = self;
    
end:
    return cell;
}

//end UITableViewDataSource

#pragma mark ProductCellButtonDelegate
- (void)onClickProductCellButton:(NSInteger)pid{
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)pid], @"pid", nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_ProductInfo];
}

- (void)onDeleteCollection:(NSInteger)pid{
    for (NSDictionary* obj in mListData) {
        if([[obj objectForKey:@"id"] integerValue] == pid){
            [mListData removeObject:obj];
            break;
        }
    }
    [self refreshView];
}
//end ProductCellButtonDelegate

#pragma mark networkDelegate

- (void)parserResult:(NSDictionary *)response functionType:(NSInteger)type
{
    if (type == NetworkFunctionType_cellection){
        if([[response objectForKey:@"status"] integerValue] == 1){
            mCurrentPage = [[response objectForKey:@"curpage"] integerValue];
            mMaxPage = [[response objectForKey:@"page"] integerValue];
            
            NSArray* adddata = [response objectForKey:@"data"];
            if(![adddata isEqual:[NSNull null]]){
                [mListData addObjectsFromArray:adddata];
            }
            
            [self refreshView];
        }
        else{
            [CommonView addAlertView:self Text:@"获取信息失败"];
        }
    }
    else if (type == NetworkFunctionType_ProductInfo){
        if([[response objectForKey:@"status"] integerValue] == 1){
            //goto productinfo view
            mProductBaseInfo = nil;
            mProductReseverInfo = nil;
            for (NSDictionary* info in mListData) {
                if([info objectForKey:@"id"]== [response objectForKey:@"id"]){
                    mProductBaseInfo = info;
                    mProductReseverInfo = [response objectForKey:@"data"];
                    break;
                }
            }
            
            if(mProductBaseInfo != nil && mProductReseverInfo != nil){
                self.tabBarController.tabBar.hidden = YES;
                [self performSegueWithIdentifier:@"collecttopinfo" sender:self];
            }
        }
        else{
            [CommonView addAlertView:self Text:@"产品列表错误"];
        }
    }
}
//end networkDelegate

- (void)prepareForSegue: (UIStoryboardSegue *)segue sender:(id)sender{
    ProductInfoController *destination = segue.destinationViewController;
    
    destination.mBaseInfo = mProductBaseInfo;
    destination.mReseverInfo = mProductReseverInfo;
}
@end
